package com.cnhaimei.vod.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Http {

	 /**
	   * 下载文件并写SD卡
	   * @param urlStr
	   * @param path
	   * @param fileName
	   * @return 0-success,-1-fail,1-existed
	   */
	public static boolean downFileToLocal(String url, String filename){
		 
		boolean bRet = true;
       if ((url!=null && !"".equals(url)) && (filename!=null && !"".equals(filename))){
       		FileOutputStream outStream = null;
           try {
               InputStream input = getInputStreamFromUrl(url);
               File outFile = new File(filename);
               outStream = new FileOutputStream(outFile);//openFileOutput(filename, Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
               int temp = 0;
               byte[] data = new byte[4096];
               while((temp = input.read(data))!=-1){
               	outStream.write(data, 0, temp);
               }
           } catch (FileNotFoundException e) {
               //toasterror("请传入正确的上下文");
               e.printStackTrace();
               bRet = false;
           } catch (IOException e) {
               //toastemessage("读写错误");
               e.printStackTrace();
               bRet = false;
           } catch (Exception e) {
				// TODO: handle exception
               e.printStackTrace();
               bRet = false;
			}
           finally{
               try {
                   outStream.flush();
                   outStream.close();
               } catch (Exception e) {
                   //toasterror("流文件未能正常关闭");
                   e.printStackTrace();
                   bRet = false;
               }
               
           }
       }

       //toastemessage("下载成功");
       return bRet;
	}
	  
	  public static  InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException,IOException{
		   URL url = new URL(urlStr);
		   HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
		   urlCon.setConnectTimeout(10*1000);
		   urlCon.setReadTimeout(10*000);
		   InputStream inputStream = urlCon.getInputStream();
		   return inputStream;
	 }
}
